package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * ClassName: RedisWorker
 * Package: IntelliJ IDEA
 * Description:
 * Written by HanXu
 * Create 2024.09.27 9:10
 */

@Component
public class RedisIdWorker {

    private static final long BEGIN_TIME = 1717200000L;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public long getGlobalId(String keyPre){

        //1 生成时间戳
        //1.1 当前时间
        LocalDateTime now = LocalDateTime.now();
        //1.2 设置时区，获取当前时间秒数
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timeStamp = nowSecond - BEGIN_TIME;

        //2 生成序列号
        //2.1 获取当前日期
        String yyyyMMdd = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //2.2 自增前缀+传入业务前缀+当前日期 组成自增value的key
        long incrCount = stringRedisTemplate.opsForValue().increment("incr:" + keyPre + ":" +yyyyMMdd);

        //3 拼接
        return timeStamp << 32 | incrCount;
    }



}
